package xiaopiya.robot.system;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class JdbcFriendService extends JdbcDaoSupport implements IFriendService
{
	private final static Log LOG = LogFactory.getLog(JdbcFriendService.class);

	private String robot = null;

	private Map<String, Friend> friends = new LinkedHashMap<String, Friend>();

	public void init(String robot, Collection<Friend> friends)
	{
		if (LOG.isInfoEnabled())
		{
			LOG.info("init[" + robot + "] with friends[" + friends + "]");
		}
		this.robot = robot;
		String sql = "select friendid, nick, bookstatus from xiaopiya_friends where robotid = ?";
		List<Friend> list = getJdbcTemplate().query(sql, new Object[]
		{ robot }, new RowMapper()
		{

			public Object mapRow(ResultSet rs, int rowNum) throws SQLException
			{
				return new Friend(rs.getString(1), rs.getString(2), rs
						.getInt(3));
			}
		});
		for (Friend friend : list)
		{
			if (LOG.isInfoEnabled())
			{
				LOG.info("load friend[" + friend + "] from db");
			}
			this.friends.put(friend.getFriendid(), friend);
		}
		for (Friend friend : friends)
		{
			addFriend(friend);
		}
	}

	public Collection<Friend> getFriends()
	{
		return this.friends.values();
	}

	public void addFriend(Friend friend)
	{
		if (!this.friends.containsKey(friend.getFriendid()))
		{
			String sql = "insert into xiaopiya_friends(robotid, friendid, nick, bookstatus) values (?, ?, ?, ?)";
			getJdbcTemplate().update(
					sql,
					new Object[]
					{ this.robot, friend.getFriendid(), friend.getNick(),
							friend.getBookstatus() });

			this.friends.put(friend.getFriendid(), friend);

			if (LOG.isInfoEnabled())
			{
				LOG.info("create friend[" + friend + "]");
			}
		}
	}

	public void changeBookStatus(String friendid, int newBookStatus)
	{
		String sql = "update xiaopiya_friends set bookstatus = ? where robotid = ? and friendid = ?";
		getJdbcTemplate().update(sql, new Object[]
		{ newBookStatus, this.robot, friendid });

		Friend friend = this.friends.get(friendid);
		friend.setBookstatus(newBookStatus);
		if (LOG.isInfoEnabled())
		{
			LOG.info("update friend[" + friend + "]");
		}
	}

	public void removeFriend(String friendid)
	{
		this.friends.remove(friendid);

		String sql = "delete from xiaopiya_friends where robotid = ? and friendid = ?";
		getJdbcTemplate().update(sql, new Object[]
		{ this.robot, friendid });

		if (LOG.isInfoEnabled())
		{
			LOG.info("update friend[" + friendid + "]");
		}
	}
}
